package leetcode.editor.cn.q1_300.q;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qidi
 * @date 2021-11-01 16:50:42
 */
class Q0018_FourSum {

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if (nums.length < 4) {
                return res;
            } else if (nums.length == 4) {
                if (Arrays.stream(nums).sum() == target) {
                    res.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
                }
            } else {
                Arrays.sort(nums);

                for (int i = 0; i < nums.length - 3; i++) {
                    if (i > 0 && nums[i] == nums[i - 1]) continue;
                    for (int j = i + 1; j < nums.length - 2; j++) {
                        if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                        int l = j + 1;
                        int r = nums.length - 1;

                        while (l < r) {
                            int tmp = nums[i] + nums[j] + nums[l] + nums[r];
                            if (tmp < target) {
                                l++;
                            } else if (tmp > target) {
                                r--;
                            } else {
                                res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                                while (l < r && nums[l] == nums[l + 1]) {
                                    l++;
                                }
                                while (l < r && nums[r] == nums[r - 1]) {
                                    r--;
                                }
                                l++;
                                r--;
                            }
                        }
                    }
                }
            }

            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0018_FourSum().new Solution();
        System.out.println(solution.fourSum(new int[]{-2, -1, -1, 1, 1, 2, 2}, 0));
        System.out.println(solution.fourSum(new int[]{2, 2, 2, 2, 2}, 8));
    }
}